<?php

class OaSales extends \Formax\Model
{

    /**
     *
     * @var integer
     */
    public $user_id;

    /**
     *
     * @var integer
     */
    public $leader;

    /**
     *
     * @var integer
     */
    public $ctime = 0;

    // 是否销售部人员
    public static function isSales($user_id)
    {
        return OaUserRoles::isRoles($user_id, array(OaRoles::SALES_DIRECTOR, OaRoles::SALES_MANANGER, OaRoles::SALES_STAFF));
    }

    // 是否销售总监
    public static function isDirector($user_id)
    {
        return OaUserRoles::isRoles($user_id, OaRoles::SALES_DIRECTOR);
    }

    // 是否销售经理
    public static function isManager($user_id)
    {
        return OaUserRoles::isRoles($user_id, OaRoles::SALES_MANANGER);
    }

    // 是否销售人员
    public static function isStaff($user_id)
    {
        return OaUserRoles::isRoles($user_id, OaRoles::SALES_STAFF);
    }

    // 获取所有记录
    public static function getAll()
    {
        static $cached = null;

        if ($cached === null) {
            $cached = array();
            foreach (self::find() as $row) {
                $cached[$row->user_id] = $row->toArray();
            }
        }

        return $cached;
    }

    // 根据用户ID，获取下属用户
    public static function getSubUsers($user_id)
    {
        $users = array($user_id);

        // 一级下属
        $childs = array_filter(self::getAll(), function ($row) use ($user_id) {
            return $row['leader'] == $user_id;
        });

        foreach ($childs as $child) {
            $users = array_merge($users, array($child['user_id']), self::getSubUsers($child['user_id']));
        }

        return array_map('intval', array_unique($users));
    }

    // 根据用户ID，获取下属销售经理
    public static function getSubManagers($user_id)
    {
        return array_filter(self::getSubUsers($user_id), function ($id) {
            return self::isManager($id) || self::isDirector($id);
        });
    }

    // 获得上级经理的ID
    public static function getParentManager($user_id)
    {
        if ($user = array_get(self::getAll(), $user_id)) {
            return $user['leader'];
        }

        return 0;
    }

}
